package com.cchc.k8s.apis;

import com.alibaba.fastjson.JSONObject;
import com.cchc.k8s.Constants;
import com.cchc.k8s.config.K8sException;
import com.google.gson.JsonSyntaxException;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1Namespace;
import io.kubernetes.client.openapi.models.V1NamespaceList;
import io.kubernetes.client.openapi.models.V1ObjectMeta;
import io.kubernetes.client.openapi.models.V1Status;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * file：NamespaceApi.java
 * description: 命名空间操作api
 * date: 2021-09-17 13:54
 * author: wenrui
 * version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/ns")
public class NamespaceApi {

    @Autowired
    ApiClient apiClient;

    /**
     * 创建命名空间
     *
     * @param name 命名空间名称
     * @throws ApiException
     */
    @GetMapping("/create/{name}")
    public V1Namespace createNamespace(@PathVariable String name) throws ApiException {
        log.info("要创建的命名空间名称为：{}", name);
        V1ObjectMeta v1ObjectMeta = new V1ObjectMeta().name(name);
        V1Namespace v1Namespace = new V1Namespace()
                .apiVersion(Constants.API_VERSION)
                .kind("Namespace")
                .metadata(v1ObjectMeta);

        CoreV1Api coreV1Api = new CoreV1Api(apiClient);
        V1Namespace namespace = coreV1Api.createNamespace(v1Namespace, "true", null, null);
        log.info("创建命名空间：{}成功，返回信息为：{}", name, JSONObject.toJSONString(namespace));
        return namespace;
    }

    /**
     * 删除命名空间
     *
     * @param name 命名空间名称
     */
    @DeleteMapping("/delete/{name}")
    public V1Status deleteNamespace(@PathVariable String name) {
        CoreV1Api coreV1Api = new CoreV1Api(apiClient);
        V1Status v1Status = null;
        try {
            v1Status = coreV1Api.deleteNamespace(name, "true", null, null, null, null, null);
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            // https://github.com/kubernetes-client/java/issues/86
            log.info("k8s-client said:I think the best you can do is catch this Exception and move on...");
            log.info("删除命名空间：{} 成功", name);
        } catch (ApiException e) {
            e.printStackTrace();
            log.error("删除命名空间:{}失败，原因：{}", name, e.getResponseBody());
            throw new K8sException("N" + e.getCode(), (String) JSONObject.parseObject(e.getResponseBody()).get("message"));
        }

        return v1Status;
    }

    /**
     * 获取所有命名空间
     *
     * @return v1NamespaceList
     * @throws ApiException
     */
    @GetMapping("/list")
    public V1NamespaceList listNamespace() throws ApiException {
        CoreV1Api coreV1Api = new CoreV1Api(apiClient);
        V1NamespaceList v1NamespaceList = coreV1Api.listNamespace("true", null, null, null, null, null, null, null, null, null);
        log.info("获取所有命名空间：{}", JSONObject.toJSONString(v1NamespaceList));
        return v1NamespaceList;
    }

    /**
     * 获取命名空间详情
     *
     * @param name 命名空间名称
     * @return V1Namespace
     */
    @GetMapping("/detail/{name}")
    public V1Namespace detailNamespace(@PathVariable String name) {
        CoreV1Api coreV1Api = new CoreV1Api(apiClient);
        V1Namespace v1Namespace;
        try {
            v1Namespace = coreV1Api.readNamespace(name, "true", null, null);
        } catch (ApiException e) {
            e.printStackTrace();
            log.error("获取命名空间：{}详情失败，原因：{}", name, e.getResponseBody());
            throw new K8sException("N" + e.getCode(), (String) JSONObject.parseObject(e.getResponseBody()).get("message"));
        }
        log.info("获取命名空间：{}详情：{}", name, JSONObject.toJSONString(v1Namespace));
        return v1Namespace;
    }
}
